#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/10/18 13:46
# @Author : 闫峰
# @File    : syc_allegro_vatiant.py
from datetime import datetime

import pymongo

from utils.mysqlUtils.mongodb_utils import MongoDBLink
import os

from common.setting import ensure_path_sep
from utils.logging_tool.log_control import LogHandler
from utils.mysqlUtils.db_pool import Database
from third_services.allegro.RebatyesAndPromotions.offerdetails import OfferDetails
from concurrent.futures import ThreadPoolExecutor, wait, as_completed
from functools import partial
import os
import time
from common.setting import ensure_path_sep
from utils.logging_tool.log_control import LogHandler
from utils.mysqlUtils.db_pool import Database

current_path = os.path.abspath(__file__)
current_dir = os.path.dirname(current_path)
path_list = current_path.split("\\")
dis_path = "\\".join(path_list[-2:-1])


def remove_file(info_path):
    if os.path.exists(info_path):
        os.remove(info_path)
    else:
        print(f"{info_path} 不存在")


info_path = ensure_path_sep(f"\\logs\\info-{dis_path}{time.time()}")
error_path = ensure_path_sep(f"\\logs\\\error-{dis_path}{time.time()}.log")
warning_path = ensure_path_sep(f"\\logs\\warning-{dis_path}{time.time()}.log")
remove_file(info_path)
remove_file(error_path)
remove_file(warning_path)
INFO = LogHandler(info_path, level='info')
ERROR = LogHandler(error_path, level='error')
WARNING = LogHandler(warning_path, level='warning')


class Syc_allegro_variant:
    a = OfferDetails()

    def test_syc_allegro_variant(self, ordersourceid):
        znkd_db = Database(ensure_path_sep("\\config\\znkd_mysql_config.yaml"), "znkd_database_prod")
        api = OfferDetails()
        variant_id_list = []
        offset_id = 0
        while True:
            res = api.get_offer_variants(ordersourceid, offset_id)
            offset_id += 10
            if res.get('offerVariants'):
                offerVariants = res.get('offerVariants')
                offerVariants_list = list(map(lambda x: x['id'], offerVariants))
                variant_id_list += offerVariants_list
                offset_id += 50
            else:
                break
        INFO.logger.info(f"ordersourceid={ordersourceid}总共有setid {len(variant_id_list)}个")
        for setid in variant_id_list:
            res1 = api.get_offer_variants_set(ordersourceid, setid)
            offerid_list = list(map(lambda x: x['id'], res1.get('offers')))
            for offerid in offerid_list:

                get_setid = """
                SELECT SetId FROM m_allegro_listing_sub WHERE CustomerId=1 AND OrderSourceId=%s AND OfferId=%s;
                """
                setid_actual = znkd_db.fetch_all(get_setid, (ordersourceid, offerid))
                if setid_actual:
                    setid_actual = setid_actual[0]['SetId']
                    if setid == setid_actual:
                        pass
                    else:
                        ERROR.logger.error(f"ordersourceid={ordersourceid} offer={offerid}的setid同步错误")
                else:
                    ERROR.logger.error(f"ordersourceid={ordersourceid} offer={offerid}的setid没有同步到")
        INFO.logger.info(f"ordersourceid={ordersourceid} setid同步验证完成")

    def run(self):
        executor = ThreadPoolExecutor(max_workers=8)
        znkd_db = Database(ensure_path_sep("\\config\\znkd_mysql_config.yaml"), "znkd_database_prod")
        # 得到所有的渠道id
        get_ordersourceid_list = """
        SELECT a.OrderSourceId FROM sys_ordersource a 
        LEFT JOIN sys_ordersource_authorization b 
        ON a.CustomerId=b.CustomerId AND a.OrderSourceId=b.OrderSourceId
        WHERE a.OrderSourceType =67
        AND a.IsActive=1 AND a.IsDelete=0 AND b.IsActive=1
        """
        ordersourceid_list = znkd_db.fetch_all_tuple(get_ordersourceid_list, ())
        ordersourceid_list = list(map(lambda x: x[0], ordersourceid_list))
        tasks = []
        INFO.logger.info(f"总共任务数{len(ordersourceid_list)}")
        for i in ordersourceid_list:
            # 使用funools.partial函数创建一个新的函数，将参数绑定到函数中
            new_task = partial(self.test_syc_allegro_variant, i)
            # executor.submit(new_task)
            tasks.append(executor.submit(new_task))

        # 处理已完成的任务
        for future in as_completed(tasks):
            try:
                result = future.result()
                # 处理任务执行的结果
                print(result)
            except Exception as e:
                # 处理任务执行出的异常
                print(f"任务{i}执行出现异常，参数为{new_task.args}")
                raise

        # 关闭线程池
        executor.shutdown()


if __name__ == '__main__':
    Syc_allegro_variant().test_syc_allegro_variant(9062)
    # Syc_allegro_variant().run()